﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Text;
using Catering.View_Operaction;
using System.IO;

namespace Catering.Catering_Page.richang
{
    public partial class rydt : System.Web.UI.Page
    {
        View_Operaction_Common voc = new View_Operaction_Common();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.TreeViewDataBind_Group(this.Tv_Group);
            }
        }

        //作业区
        public void TreeViewDataBind_Group(TreeView tv)
        {
            tv.Nodes.Clear();
            Catering_Rules.OperationArea crr = new Catering_Rules.OperationArea();
            DataSet ds_OperationArea = null;
            int companyid = 0;
            if (Session["UserID"] != null)
            {
                string userid = Session["UserID"].ToString();
                companyid = new Catering_Rules.T_Personnel().GetCompanyIDByPID(Convert.ToInt32(userid));
                if (companyid > 0) ds_OperationArea = crr.GetAllListByCompanyID(companyid);
            }

            TreeNode tn_all = new TreeNode("全部", companyid.ToString(), "", "", "typeall");
            tv.Nodes.Add(tn_all);

            foreach (DataRow dr_OperationArea in ds_OperationArea.Tables[0].Rows)
            {
                if (dr_OperationArea["AreaName"] != null)
                {
                    TreeNode tn_RawMaterials = new TreeNode();
                    tn_RawMaterials.Text = dr_OperationArea["AreaName"].ToString();
                    tn_RawMaterials.Value = dr_OperationArea["id"].ToString();
                    tn_RawMaterials.Target = "type";
                    //--------------添加子节点-----------------------------------//
                    TreeViewDataBing_ClassInfo(tn_RawMaterials, dr_OperationArea["id"].ToString());
                    tn_all.ChildNodes.Add(tn_RawMaterials);
                }
            }
        }

        //班组
        private void TreeViewDataBing_ClassInfo(TreeNode tn, string tvNodeId)
        {
            Catering_Rules.ClassInfo crr = new Catering_Rules.ClassInfo();
            DataSet ds_ClassInfo = crr.GetList("AreaID=" + tvNodeId);
            foreach (DataRow dr_ClassInfo in ds_ClassInfo.Tables[0].Rows)
            {
                if (dr_ClassInfo["CName"] != null)
                {
                    TreeNode tn_ClassInfo = new TreeNode();
                    tn_ClassInfo.Text = dr_ClassInfo["CName"].ToString();
                    tn_ClassInfo.Value = dr_ClassInfo["id"].ToString();
                    tn_ClassInfo.Target = "typeinfo";
                    tn.ChildNodes.Add(tn_ClassInfo);
                }
            }
        }

        protected void Tv_Group_SelectedNodeChanged(object sender, EventArgs e)
        {
            this.Txt_ClassName.Value = "";
            this.Txt_ZNumber.Value = "";
            this.Txt_PNumber.Value = "";
            this.Txt_DNumber.Value = "";
            this.Txt_QNumber.Value = "";

            if (this.Txt_Stata_Date.Text.Trim() == "" || this.Txt_Stop_Date.Text.Trim() == "")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('请选择日期')", true);
                return;
            }

            Catering_Rules.Dynamics crd = new Catering_Rules.Dynamics();
            string strWhere = "";//配餐条件
            string strWhere_Dynamic = "";//主表条件
            string strAttendanceRecord = "";//配餐人员
            if (this.Tv_Group.SelectedNode.Target == "typeinfo")
            {
                strWhere = "AND ClassID=" + this.Tv_Group.SelectedValue + " and Dates between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')";
                strWhere_Dynamic = " ClassID=" + this.Tv_Group.SelectedValue + " and [Date] between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')";
                strAttendanceRecord = " ClassID=" + this.Tv_Group.SelectedValue + " and [Date] between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')  AND State=1 ";
            }
            else if (this.Tv_Group.SelectedNode.Target == "type")
            {
                strWhere = "AND GroupID=" + this.Tv_Group.SelectedValue + " and Dates between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')";
                strWhere_Dynamic = " GroupID=" + this.Tv_Group.SelectedValue + " and [Date] between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')";

                DataTable dt_classinfo = new Catering_Rules.ClassInfo().GetList("AreaID=" + this.Tv_Group.SelectedValue).Tables[0];
                string strclassid = "";
                foreach (DataRow row_class in dt_classinfo.Rows)
                {
                    strclassid += row_class["id"].ToString() + ",";
                }
                strAttendanceRecord = " ClassID in (" + strclassid.TrimEnd(',') + ") and [Date] between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')  AND State=1 ";
            }
            else
            {
                int id = 0;
                Int32.TryParse(this.Tv_Group.SelectedValue, out id);
                string arealist = new Catering_Rules.OperationArea().GetStrAreaIDListByCompanyID(id);
                strWhere = "AND GroupID IN (" + arealist + ") and Dates between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')";
                strWhere_Dynamic = " GroupID IN (" + arealist + ") and [Date] between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')";
                strAttendanceRecord = " [Date] between CONVERT(datetime,'" + this.Txt_Stata_Date.Text.Trim() + "') and CONVERT(datetime,'" + this.Txt_Stop_Date.Text.Trim() + "')  AND State=1 ";
            }


            //int zrs = 0;//总人数
            int pcrs = 0;//配餐人数
            int dy = 0;//定员人数
            int qtrs0 = 0;//其他人数

            DataTable dt_Dynamics = new Catering_Rules.Dynamics().GetListGroupByDanWei(strWhere, "temp1").Tables[0];
            if (dt_Dynamics != null && dt_Dynamics.Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                int i = 0;
                foreach (DataRow row in dt_Dynamics.Rows)
                {
                    i += 1;
                    decimal specialrate = 0;
                    string classid = "0";
                    if (this.Tv_Group.SelectedNode.Target == "typeinfo")
                    {
                        classid = this.Tv_Group.SelectedNode.Value;
                    }
                    if (!(row["SpecialRate"] is DBNull) && !string.IsNullOrEmpty(row["SpecialRate"].ToString()))
                    {
                        Decimal.TryParse(row["SpecialRate"].ToString(), out specialrate);
                        specialrate = Toolss.GetMathResult(specialrate, 1, 3);
                    }
                    sb.Append("<tr> ");
                    sb.Append("<td>" + i.ToString() + "</td>");
                    sb.Append("<td>" + row["temp1"].ToString() + "</td>");
                    sb.Append("<td>" + row["Eat"].ToString() + "</td>");
                    //48：渤西终端，2：精细化工，4：绥中终端，30：渤南终端
                    if (classid == "48" || classid == "2" || classid == "4" || classid == "30")
                    {
                        sb.Append("<td>" + specialrate + "</td>");
                    }
                    else
                    {
                        sb.Append("<td>&nbsp;</td>");
                    }
                    sb.Append("</tr>");
                    qtrs0 += Convert.ToInt32(row["Eat"].ToString());
                }
                ViewState["ShowHtml"] = sb.ToString();
            }
            else
            {
                ViewState["ShowHtml"] = "";
            }

            //人员动态
            DataTable dt_Dynamic = new Catering_Rules.Dynamic().GetList(strWhere_Dynamic).Tables[0];
            if (dt_Dynamic != null && dt_Dynamic.Rows.Count > 0)
            {
                foreach (DataRow dr in dt_Dynamic.Rows)
                {
                    dy += Convert.ToInt32(dr["persons"]);
                }
            }

            //配餐人员
            DataTable dt_AttendanceRecord = new Catering_Rules.AttendanceRecord().GetList(strAttendanceRecord).Tables[0];
            if (dt_AttendanceRecord != null && dt_AttendanceRecord.Rows.Count > 0)
            {
                pcrs = dt_AttendanceRecord.Rows.Count;
            }

            this.Txt_ClassName.Value = this.Tv_Group.SelectedNode.Text;
            this.Txt_ZNumber.Value = (dy + qtrs0).ToString();
            this.Txt_PNumber.Value = pcrs.ToString();
            this.Txt_DNumber.Value = dy.ToString();
            this.Txt_QNumber.Value = qtrs0.ToString();//Numbers[3].ToString();
        }

        //导出
        protected void but_Execl_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.Tv_Group.SelectedNode;
            string groupid = "-10";
            string classid = "-10";
            int infotype = 0;//0：全部 1：作业区 2：班组
            string strtype = "全部作业区就餐人员动态";
            if (this.Tv_Group.SelectedNode.Target == "typeinfo")
            {
                infotype = 2;
                strtype = this.Tv_Group.SelectedNode.Parent.Text + this.Tv_Group.SelectedNode.Text + "就餐人员动态";
                classid = this.Tv_Group.SelectedNode.Value;
                groupid = this.Tv_Group.SelectedNode.Parent.Value;
            }
            else if (this.Tv_Group.SelectedNode.Target == "type")
            {
                infotype = 1;
                strtype = this.Tv_Group.SelectedNode.Parent.Text + "就餐人员动态";
                groupid = this.Tv_Group.SelectedNode.Value;
            }

            if (tn != null)
            {
                DataTable dt = new Catering.View_Operaction.Richang_Manage_Operaction().Seacher_Jiucan(groupid, classid, this.Txt_Stata_Date.Text.Trim(), this.Txt_Stop_Date.Text.Trim(), infotype);
                Microsoft.Office.Interop.Excel.Application excel1 = null;
                Microsoft.Office.Interop.Excel._Worksheet ws = null;
                Microsoft.Office.Interop.Excel.Range canbie = null;
                string stick = DateTime.Now.Ticks.ToString();

                try
                {
                    excel1 = new Microsoft.Office.Interop.Excel.Application();
                    excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                    //Microsoft.Office.Interop.Excel._Worksheet ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                    ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                    ws = (Microsoft.Office.Interop.Excel._Worksheet)excel1.ActiveSheet;//获取当前活动工作薄
                    ////Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                    excel1.Visible = false;

                    #region  表头


                    canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 3]);
                    canbie.MergeCells = true;//合并单元格
                    canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中
                    canbie.Font.Bold = 2;
                    ws.Cells[1, 1] = this.Txt_Stata_Date.Text.Trim() + "到" + this.Txt_Stop_Date.Text.Trim() + strtype;

                    #endregion

                    #region 第一行标题
                    ws.Cells[2, 1] = "序号";
                    ws.Cells[2, 2] = "就餐人员单位";
                    ws.Cells[2, 3] = "就餐人数";

                    #endregion

                    #region 内容

                    int canbiehangshu = 3;//行数
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string name = dt.Rows[i]["temp1"].ToString();
                            string eat = dt.Rows[i]["Eat"].ToString();

                            ws.Cells[canbiehangshu, 1] = (i + 1);
                            ws.Cells[canbiehangshu, 2] = name;
                            ws.Cells[canbiehangshu, 3] = eat;
                            canbiehangshu++;
                        }
                        dt.Dispose();
                    }
                    ws.Cells.EntireColumn.AutoFit();
                    canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[canbiehangshu - 1, 3]);
                    canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中
                    canbie.Borders.LineStyle = 1;

                    #endregion

                    if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                    ws.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
                }
                finally
                {
                    if (excel1 != null)
                    {
                        if (ws != null)
                        {
                            if (canbie != null)
                            {
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(canbie);
                                canbie = null;

                            }
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                            ws = null;
                        }
                        excel1.Application.Workbooks.Close();
                        excel1.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                        Toolss.KillExcel(excel1);
                        excel1 = null;
                        GC.Collect();
                    }
                }

                #region 发送

                try
                {
                    string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                    System.IO.FileInfo file = new System.IO.FileInfo(path);
                    Response.Clear();
                    Response.Charset = "GB2312";
                    Response.ContentEncoding = System.Text.Encoding.UTF8;
                    // 添加头信息，,弹出另存为窗口  
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                    //让浏览器头显示下载信息  
                    Response.AddHeader("Content-Length", file.Length.ToString());
                    // 指定返回一个不能被客户端读取的流，下载  
                    Response.ContentType = "application/ms-excel";
                    //把文件流下载到客户端  
                    Response.WriteFile(file.FullName);
                    // 停止页面的执行
                    Response.End();
                }
                catch
                {
                }

                #endregion
            }
        }
    }
}